/*
 * Copyright (c) 2022. China Mobile (SuZhou) Software Technology Co.,Ltd. All rights reserved.
 * Lakehouse is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

package com.chinamobile.cmss.lakehouse.dao;

import com.chinamobile.cmss.lakehouse.dao.entity.EventEntity;
import com.chinamobile.cmss.lakehouse.dao.repository.EventRepository;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(rollbackFor = Exception.class)
public class EventDao {

    @Autowired
    private EventRepository eventRepository;

    public void addEvent(String instanceId, String event) {
        EventEntity eventEntity = new EventEntity();
        eventEntity.setInstanceId(instanceId);
        eventEntity.setEvent(event);
        eventEntity.setTime(new Date());

        eventRepository.save(eventEntity);
    }

    public List<EventEntity> getEventList(String instanceId, String event, Date startTime, Date endTime) {
        return eventRepository.findByInstanceIdAndEventAndTimeBetween(instanceId, event, startTime,
            endTime);
    }

    public EventEntity getLastEventBefore(String instanceId, Date startTime) {

        List<EventEntity> eventList =
            eventRepository.findByInstanceIdAndTimeBeforeOrderByTimeDesc(instanceId, startTime);
        if (eventList == null || eventList.size() == 0) {
            return null;
        }
        return eventList.get(0);
    }

    public EventEntity getLastEventBetween(String instanceId, Date startTime, Date endTime) {

        List<EventEntity> eventList = eventRepository
            .findByInstanceIdAndTimeBetweenOrderByTimeDesc(instanceId, startTime, endTime);
        if (eventList == null || eventList.size() == 0) {
            return null;
        }
        return eventList.get(0);
    }
}
